package com.ho1ho.springboot.framework.core.utils;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.RequestContextUtils;

@Component
public class MessageManager {

    private static MessageSource messageSource;	
	
	public static String getMsg(String key) {
		Locale locale = LocaleContextHolder.getLocale();
		return MessageManager.getMsg(key, locale);
	}
	public static String getMsg(String key, HttpServletRequest request) {
		Locale locale = RequestContextUtils.getLocale(request);
		return MessageManager.getMsg(key, locale);
	}
	public static String getMsg(String key, Locale locale) {
		return messageSource.getMessage(key, null, locale);
	}
	
	public static String getMsg(String key, String... arg) {
		Locale locale = LocaleContextHolder.getLocale();
		return MessageManager.getMsg(key, locale, arg);
	}
	public static String getMsg(String key, HttpServletRequest request, String... arg) {
		Locale locale = RequestContextUtils.getLocale(request);
		return MessageManager.getMsg(key, locale, arg);
	}
	public static String getMsg(String key, Locale locale, String... arg) {
	    Object[] args = new Object[arg.length];
	    for (int i = 0; i < arg.length; i++) {
	    	args[i] = arg[i];
	    }
	    return messageSource.getMessage(key, args, locale);
	}
	
	@Autowired(required = true)
	public void setMessageSource(MessageSource messageSource) {
		MessageManager.messageSource = messageSource;
	}
}
